
package com.kugou.game.sdk.core;

import java.util.HashMap;

import android.content.Context;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.kugou.framework.base.LogUtil;

/**
 * 描述:位置信息管理类
 * 
 * @author chenys
 * @since 2013-10-30 下午5:30:50
 */
public class LocationManager {

    private static LocationManager mLocationManager;

    private LocationClient mLocationClient = null;

    private HashMap<String, Object> mObjHolder = new HashMap<String, Object>();

    private Context mContext;

    private LocationManager(Context context) {
        this.mContext = context.getApplicationContext();
        mLocationClient = new LocationClient(context);
        initLocSeting();
    }

    public static synchronized LocationManager getInstance(Context context) {
        if (mLocationManager == null) {
            mLocationManager = new LocationManager(context);
        }
        return mLocationManager;
    }

    // 设置百度定位基本参数
    private void initLocSeting() {
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);
        option.setAddrType("all");// 返回的定位结果包含地址信息
        option.setCoorType("bd09ll");// 返回的定位结果是百度经纬度,默认值gcj02
        option.setScanSpan(5000);// 设置发起定位请求的间隔时间为5000ms
        option.disableCache(true);// 禁止启用缓存定位
        option.setPoiNumber(5); // 最多返回POI个数
        option.setPoiDistance(1000); // poi查询距离
        option.setPoiExtraInfo(true); // 是否需要POI的电话和地址等详细信息
        mLocationClient.setLocOption(option);
    }

    /**
     * 请求当前位置信息
     * 
     * @param listener
     */
    public void requestLocation() {
        mLocationClient.registerLocationListener(mBDLocationListener);
        mLocationClient.start();
        if (mLocationClient != null && mLocationClient.isStarted()) {
            mLocationClient.requestLocation();
        } else {
            LogUtil.d("111", "locClient is null or not started");
        }
    }

    public void stop() {
        mLocationClient.stop();
    }

    /**
     * 百度定位监听
     */
    private BDLocationListener mBDLocationListener = new BDLocationListener() {
        @Override
        public void onReceivePoi(BDLocation location) {
        }

        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location != null) {
                mObjHolder.put("location", location);
                LocationManager.getInstance(mContext).stop();
            }
        }
    };

    /**
     * 获取用户的地理位置信息
     * 
     * @return BDLocation 地理位置信息
     */
    public BDLocation getLocation() {
        if (mObjHolder != null) {
            return (BDLocation) mObjHolder.get("location");
        }
        return null;
    }

}
